import threading
import time
import sys

class ProgressThread(threading.Thread):
    def __init__(self, thread_id, total, progress_list):
        super().__init__()
        self.thread_id = thread_id
        self.total = total
        self.current = 0
        self.progress_list = progress_list

    def run(self):
        while self.current < self.total:
            time.sleep(0.1)  # 模拟工作
            self.current += 1
            self.update_progress()

    def update_progress(self):
        percent = (self.current / self.total) * 100
        self.progress_list[self.thread_id - 1] = (self.thread_id, self.current, percent)

def print_all_progress(progress_list):
    sys.stdout.write("\033[F" * (len(progress_list) + 1))  # 移动光标到上方
    for thread_id, current, percent in progress_list:
        bar_length = 40
        filled_length = int(bar_length * current // total_items)
        bar = '█' * filled_length + '-' * (bar_length - filled_length)
        sys.stdout.write(f'线程 {thread_id}: |{bar}| {percent:.2f}% 完成\n')  # 每个线程换行
    sys.stdout.flush()

# 示例用法
if __name__ == "__main__":
    total_items = 100
    threads = []
    progress_list = [(i + 1, 0, 0.0) for i in range(5)]  # 初始化进度列表

    for i in range(5):  # 创建5个线程
        thread = ProgressThread(thread_id=i + 1, total=total_items, progress_list=progress_list)
        threads.append(thread)
        thread.start()

    while any(thread.is_alive() for thread in threads):  # 当有线程在运行时
        print_all_progress(progress_list)
        time.sleep(0.1)  # 刷新间隔

    for thread in threads:
        thread.join()  # 等待所有线程完成

    # 打印所有线程已完成的信息，不换行
    sys.stdout.write("\r所有线程已完成\n")
    sys.stdout.flush()